package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.databinding.ActivityLocalPlayBinding;
import flc.ast.dialog.DeleteDialog;
import flc.ast.dialog.MoveDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class LocalPlayActivity extends BaseAc<ActivityLocalPlayBinding> {

    private SelVideoAdapter videoAdapter;
    private List<String> listSel = new ArrayList<>();
    private boolean isEdit = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_local_play;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivLocalPlayBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvManage.setOnClickListener(this);
        mDataBinding.tvClear.setOnClickListener(this);
        mDataBinding.tvCancel.setOnClickListener(this);
        mDataBinding.tvMove.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);

        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 3));
        videoAdapter = new SelVideoAdapter();
        videoAdapter.setEdit(false);
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvManage://管理
                isEdit = true;
                videoAdapter.setEdit(isEdit);
                videoAdapter.notifyDataSetChanged();
                mDataBinding.llBottom.setVisibility(View.GONE);
                mDataBinding.llEdit.setVisibility(View.VISIBLE);
                break;
            case R.id.tvClear://清空
                listSel.clear();
                for (SelectMediaEntity validDatum : videoAdapter.getValidData()) {
                    listSel.add(validDatum.getPath());
                }
                delete();
                break;
            case R.id.tvCancel://取消
                cancelEdit();
                break;
            case R.id.tvMove://移动至
                if (listSel.size() == 0) {
                    ToastUtils.showShort(getString(R.string.please_sel_video));
                    return;
                }
                showMoveDialog();
                break;
            case R.id.tvDelete://删除
                if (listSel.size() == 0) {
                    ToastUtils.showShort(getString(R.string.please_sel_video));
                    return;
                }
                showDeleteDialog();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (videoAdapter.getItem(position).isChecked()) {
                videoAdapter.getItem(position).setChecked(false);
                listSel.remove(videoAdapter.getItem(position).getPath());
            } else {
                videoAdapter.getItem(position).setChecked(true);
                listSel.add(videoAdapter.getItem(position).getPath());
            }
            videoAdapter.notifyItemChanged(position);
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(videoAdapter.getItem(position).getUri()), "video/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    videoAdapter.setList(selectMediaEntities);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                }
            }
        });
    }

    private void showMoveDialog() {
        MoveDialog moveDialog = new MoveDialog(mContext);
        moveDialog.setListener(new MoveDialog.Ilistener() {
            @Override
            public void click() {
                saveFileToPrivacy();
            }
        });
        moveDialog.show();
    }

    //保存选择文件到私密视频
    private void saveFileToPrivacy() {
        showDialog(getString(R.string.saving));
        RxUtil.create(new RxUtil.Callback<String>() {

            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                for (String path : listSel) {
                    String filePath = FileUtil.generateFilePath(Content.myPrivacy, "." + FileUtils.getFileExtension(path));
                    FileUtils.copy(path, filePath);
                }
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                dismissDialog();
                cancelEdit();
            }
        });
    }

    private void showDeleteDialog() {
        DeleteDialog deleteDialog = new DeleteDialog(mContext);
        deleteDialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                delete();
            }
        });
        deleteDialog.show();
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        for (String s : listSel) {
                            FileUtils.delete(s);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        cancelEdit();
                    }
                });
            }
        }, 1000);
    }

    private void cancelEdit() {
        isEdit = false;
        videoAdapter.setEdit(false);
        getData();
        mDataBinding.llBottom.setVisibility(View.VISIBLE);
        mDataBinding.llEdit.setVisibility(View.GONE);
    }

}